﻿using System;
using System.Linq;
using System.Windows.Controls;
using System.Xml.Linq;
using Hardcodet.Wpf.TaskbarNotification;

namespace Songhay.Wpf.UriTree.Managers
{
    using Models;
    using Properties;
    using Songhay.Data.Linq.Opml;
    using Songhay.Xml;

    /// <summary>
    /// Interaction logic for <c>Hardcodet.Wpf.TaskbarNotification</c> visuals.
    /// </summary>
    public partial class TaskbarIconManager : IDisposable
    {
        void LoadChildItems(MenuItem menu, XElement element, IOpmlSet opml, string namePrefix)
        {
            if(menu == null) throw new ArgumentNullException("menu", "The menu item is null.");
            if(element == null) throw new ArgumentNullException("elements", "The child elements are null.");

            var categories = XObjectUtility.GetXElements(element, Settings.Default.XpathUriCategories);
            var resources = XObjectUtility.GetXElements(element, Settings.Default.XpathUriResources);

            var counter = 0;
            if(categories != null)
            {
                categories.ToList().ForEach(c =>
                {
                    var displayName = XObjectUtility.GetValue(c, Settings.Default.XpathUriName);
                    if(c.HasElements)
                    {
                        //Recur:
                        var item = new MenuItem
                        {
                            Header = displayName,
                            Name = string.Concat(namePrefix, counter)
                        };
                        item.Icon = this.GetImage(TaskBarIconName.Folder);
                        this.LoadChildItems(item, c, opml, namePrefix);
                        menu.Items.Add(item);
                        this.RecordLastLoadedNode(displayName);
                    }
                });
            }

            if(resources == null) return;
            counter = 0;
            resources.ToList().ForEach(r =>
            {
                var displayName = XObjectUtility.GetValue(r, Settings.Default.XpathUriName);
                var resource = XObjectUtility.GetValue(r, Settings.Default.XpathUriValue);
                var item = new MenuItem
                {
                    Header = displayName,
                    Name = string.Concat(namePrefix, counter),
                    Tag = resource
                };
                item.Click += (s, args) =>
                {
                    #region handle item click:

                    if((s == null) || !(s is MenuItem)) return;
                    var mItem = s as MenuItem;
                    var command = mItem.Tag.ToString();
                    command = command.Trim();

                    if(string.IsNullOrEmpty(command)) return;

                    var location = Environment.ExpandEnvironmentVariables(command);
                    if(Uri.IsWellFormedUriString(location, UriKind.Absolute))
                    {
                        Framework.StartProcess(location, ClientContainer.AlternateBrowser, ClientContainer.UseAlternateBrowser);
                    }
                    else
                    {
                        try
                        {
                            Framework.StartProcess(command);
                        }
                        catch(System.ComponentModel.Win32Exception ex)
                        {
                            if(ex.ErrorCode == -2147467259)
                            {
                                string msg = string.Format("Can’t open this file: “{0}”", command);
                                this.ShowBalloonMessage(msg, BalloonIcon.Error);
                            }
                            else
                            {
                                this.ShowBalloonMessage(string.Concat(ex.Message, Environment.NewLine, ex.StackTrace), BalloonIcon.Error);
                            }
                        }
                        catch(Exception ex)
                        {
                            this.ShowBalloonMessage(string.Concat(ex.Message, Environment.NewLine, TaskbarIconManager.OpmlMetaData.LastLoadedNode), BalloonIcon.Error);
                        }
                    }

                    #endregion
                };
                item.Icon = this.GetImage(TaskBarIconName.Node);
                menu.Items.Add(item);
                this.RecordLastLoadedNode(displayName);
            });

            var elementCount = element.Elements().Count();
            if(elementCount != (categories.Count() + resources.Count()))
            {
                throw new Exception(@"
Data Format Error:

The number of child nodes is not the same
as selected categories and resources
for this subtree.

Correct the XML file containing the last loaded node.
");
            }
        }
    }
}
